package main

import (
	"bufio"
	"crypto/tls"
	"crypto/x509"
	"io/ioutil"
	"log"
	"net"
)

func main() {

	cert, err := tls.LoadX509KeyPair("server.crt", "server.key")
	if err != nil {
		log.Panicln(err)
	}

	pool := x509.NewCertPool()
	caCertPath := "ca.crt"

	caCrt, err := ioutil.ReadFile(caCertPath)
	if err != nil {
		log.Panicln("ReadFile err:", err)
	}
	if ok := pool.AppendCertsFromPEM(caCrt); !ok {
		log.Panicln("failed to parse root certificate")
	}

	config := &tls.Config{
		Certificates:       []tls.Certificate{cert},
		ClientAuth:         tls.RequireAndVerifyClientCert,
		ClientCAs:          pool,
		InsecureSkipVerify: false,
	}
	ln, err := net.Listen("tcp", ":1443")
	//ln, err := tls.Listen("tcp", ":1443", config)
	if err != nil {
		log.Panicln("Listen err:", err)
	}
	defer ln.Close()
	log.Println("开始监听@1443")
	for {
		conn, err := ln.Accept()
		if err != nil {
			log.Println("Accept err:", err)
			continue
		}
		c := tls.Server(conn, config)
		if err := c.Handshake(); err != nil {
			log.Println("证书校验失败 err:", err)
			conn.Close()
			continue
		}
		info:=c.ConnectionState().PeerCertificates[0]

		for _,v:=range info.Subject.Names{
			log.Println(v.Type,v.Value)
		}
		//buf,err:=json.Marshal(info.Subject)
		//log.Println(info.Subject)
		//log.Println("Subject",string(buf))
		log.Println(info.NotBefore)
		log.Println(info.NotAfter)
		defer conn.Close()

		go handleConn(c)
	}
}
func handleConn(conn *tls.Conn) {

	r := bufio.NewReader(conn)
	for {
		msg, err := r.ReadString('\n')

		if err != nil {
			log.Println("ReadString err:", err)
			return
		}
		log.Println(msg)
		_, err = conn.Write([]byte("world\n"))
		if err != nil {
			log.Println("Write err:", err)
			return
		}
	}
}
